package GUILayer;

import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;

import javax.swing.*;
import javax.swing.table.*;

import CtrLayer.ProductCtr;
import ModelLayer.Product;

public class ProductGUI {
	
	private static int idP = 1000;
    private static ProductCtr productCtr = new ProductCtr();
    private JPanel panel;
    private JTable productTable;
    private Object[][] data;	// table data
    private int size; 			// table no. of rows
    private final DateFormat toFormat = new SimpleDateFormat("dd/MM/yyyy");
    
	public ProductGUI()
	{
		
	}
	
	
	
	private JPanel makeSearchPanel()
	{
		JPanel panel = new JPanel();
		int sp=8;
		panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Search"),BorderFactory.createEmptyBorder(sp, sp, sp, sp)));
		
		JLabel idORname = new JLabel("ID or Name");
		final JTextField field = new JTextField(10);
		JButton but1 = new JButton("Search");
		
		but1.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent ev) {
				
				try{
					String searchBY = field.getText();
					
					int rowHigh = -1;
					for(int i=0;i<size;i++)
						if( data[i][0].toString().equals(searchBY) || (data[i][1]).equals(searchBY) ) {rowHigh = i;break;}
					
					if(rowHigh>=0) 
					{
						productTable.setRowSelectionInterval(rowHigh, rowHigh);
						productTable.scrollRectToVisible(productTable.getCellRect(rowHigh,0, true)); 
					}
				}
				catch(Exception ex){}
				
			}
			
		});
		
		panel.add(idORname);
		panel.add(field);
		panel.add(but1);
		
		return panel;
	}
	
	
	
	private JPanel makeAddProductPanel()
	{
		JPanel addPanel = new JPanel();
		GridLayout grid = new GridLayout(0,2);
		grid.setVgap(4);
		
		addPanel.setLayout(grid);
		
		String[] addProductFields = {"Name","Description","Price","Stock","Warehouse"};
		final JTextField[] addProductTextFields = new JTextField[5];
		
		for(int i=0;i<addProductFields.length;i++)
		{
			JLabel fieldL = new JLabel(addProductFields[i]);
			addProductTextFields[i] = new JTextField(15);
			
			addPanel.add(fieldL);
			addPanel.add(addProductTextFields[i]);
		}
		
		JPanel errMess = new JPanel();
		final JLabel errors = new JLabel();
		errors.setForeground(Color.red);
		errMess.add(errors);
		
		
		JPanel addProductMain = new JPanel();
		addProductMain.setLayout(new BoxLayout(addProductMain, BoxLayout.Y_AXIS));
		int sp=8;
		addProductMain.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Add Product"),BorderFactory.createEmptyBorder(sp, sp, sp, sp)));
		
		
		addProductMain.add(addPanel);
		addProductMain.add(errMess);
		
		
		JButton addProdButton = new JButton("Add Product");
		addProdButton.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent e) {
				String error = "";
				
				String name = addProductTextFields[0].getText();
				String desc = addProductTextFields[1].getText();
				double price = 0;
				int stock = -1;
				String location = addProductTextFields[4].getText();
				
				try{price = Double.parseDouble(addProductTextFields[2].getText());}
				catch(Exception ex){}
				
				try{stock = Integer.parseInt(addProductTextFields[3].getText());}
				catch(Exception ex){}
				
				if(name.isEmpty()) error = "The name is empty";
				else if(desc.isEmpty()) error = "The description is empty";
				else if(price==0) error = "The price is invalid";
				else if(stock==-1) error = "The stock is invalid";
				else if(location.isEmpty()) error = "The warehouse is empty";
				
				if(error!="")
				{
					errors.setText(error);
				}
				else
				{
					errors.setText("");
					productCtr.addProduct(idP,name,desc,price,location,stock);
					idP++;
					reAddGrid();
				}
			}
			
		});

		
		addPanel.add(new JLabel());
		addPanel.add(addProdButton);
		
		
		return addProductMain;
	}
	
	
	
	private JPanel makeGridListProducts()
	{
		Iterator<?> it = productCtr.getProductsIterator();
		size = productCtr.getProductsSize();
        
		String[] columnNames = {"Id","Name","Stock","Price","Discount","Final Price","End date","Warehouse","Delete"};
		data = new Object[size][columnNames.length];
		
		int i=0;
		while(it.hasNext())
		{
			Product prod = (Product)it.next();
			data[i][0]= prod.getId();
			data[i][1]= prod.getName();
			data[i][2]= prod.getStock();
			data[i][3]= prod.getPrice();
			data[i][4]= prod.getDiscount();
			data[i][5]= prod.getFinalPrice();
			data[i][6]= toFormat.format(prod.getEndDateDiscount()).toString();
			data[i][7]= prod.getLocation();
			data[i][8]= Boolean.FALSE;
			i++;
		}
		
		JPanel gridProducts = new JPanel();
		DefaultTableModel dtm = new DefaultTableModel(data,columnNames){
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int col){		// <-- override for non-editable cells
				return (col==8);
			}
			
			public Class<?> getColumnClass(int col) {
			    if(col == 8) return Boolean.class;
			    return super.getColumnClass(col);
			}
		};
		

		
		
		productTable = new JTable(dtm);
		productTable.getTableHeader().addMouseListener(new MouseAdapter(){
			public void mouseClicked(MouseEvent e) {
				int col = productTable.columnAtPoint(e.getPoint());
				if(col==8)
				{
					if(Main.access==false)	
					{
						JOptionPane.showConfirmDialog(null, "You don't have access","Info",JOptionPane.CLOSED_OPTION);
						return;
					}
					
					int selected = getSelectedProducts(productTable);
					if(selected==0)
					{
						JOptionPane.showConfirmDialog(null, "You didn't selected any products","Info",JOptionPane.CLOSED_OPTION);
					}
					else
					{
						int answer = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete "+ selected +" product(s) ?","Confirm delete",JOptionPane.YES_NO_OPTION);
						if(answer == JOptionPane.YES_OPTION)
						{
							deleteSelectedProducts(productTable);
						}
					}
				}
			}
		});
		
		
		
		TableColumnModel tcm = productTable.getColumnModel();
		tcm.getColumn(0).setPreferredWidth(40);  
		tcm.getColumn(2).setPreferredWidth(40);
		tcm.getColumn(3).setPreferredWidth(63);
		
		JScrollPane productTableScroll = new JScrollPane(productTable);
		productTableScroll.setPreferredSize(new Dimension(600,200));
		productTableScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		productTableScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		
		gridProducts.add(productTableScroll,BorderLayout.CENTER);
		
		
		
		productTable.addMouseListener(new MouseAdapter(){
			
			public void mouseClicked(MouseEvent e)
			{
				if(e.getClickCount()==2)
				{
					JTable target = (JTable)e.getSource();
					int row = target.getSelectedRow();
					int idProduct = 0;
					try{ 
						idProduct = (Integer)target.getModel().getValueAt(row, 0);
						productFrame(idProduct);
					}
					catch(Exception ex){}
				}
			}
			
		});
		
		return gridProducts;
	}
	
	
	private void productFrame(int idP)
	{
		final JFrame frame = new JFrame("Product id "+idP);
		JPanel mainPanel = new JPanel();
		
		try{
			final Product product = productCtr.getProduct(idP);
			
			JLabel lab1 = new JLabel("Id");
			JLabel lab2 = new JLabel("Name");
			JLabel lab3 = new JLabel("Location");
			JLabel lab4 = new JLabel("Stock");
			
			JLabel lab5 = new JLabel("Price");
			JLabel lab6 = new JLabel("Discount(%)");
			JLabel lab7 = new JLabel("Final price");
			JLabel lab8 = new JLabel("End date");
			
			
			JLabel lab9 = new JLabel("Description");
			
			int cols = 6;
			JLabel llab1 = new JLabel();
			final JTextField llab2 = new JTextField(cols);
			final JTextField llab3 = new JTextField(cols);
			final JTextField llab4 = new JTextField(cols);
			
			final JTextField llab5 = new JTextField(cols);
			final JTextField llab6 = new JTextField(cols);
			JLabel llab7 = new JLabel();
			final JTextField llab8 = new JTextField(cols);
			
			final JTextArea llab9 = new JTextArea(4,19);
			JScrollPane llab9Scroll = new JScrollPane(llab9);
			llab9Scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
			llab9Scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
			
			llab1.setText(String.valueOf(product.getId()));
			llab2.setText(product.getName());
			llab3.setText(product.getLocation());
			llab4.setText(String.valueOf(product.getStock()));
			llab5.setText(String.valueOf(product.getPrice()));
			llab6.setText(String.valueOf(product.getDiscount()));
			llab7.setText(String.valueOf(product.getFinalPrice()));
			
			llab9.setText(product.getDescription());
			
			Date date = product.getEndDateDiscount();
			
			llab8.setText(toFormat.format(date));
			
			JPanel grid1 = new JPanel();
			JPanel grid2 = new JPanel();
			JPanel grid3 = new JPanel();
			
			GridLayout gridLay = new GridLayout(0,2);
			GridLayout gridLay3 = new GridLayout(0,2);
			
			gridLay3.setHgap(20);
			
			grid1.setLayout(gridLay);
			grid2.setLayout(gridLay);
			grid3.setLayout(gridLay3);
			
			grid1.add(lab1);
			grid1.add(llab1);
			
			grid1.add(lab2);
			grid1.add(llab2);
			
			grid1.add(lab3);
			grid1.add(llab3);
			
			grid1.add(lab4);
			grid1.add(llab4);
			
			grid2.add(lab5);
			grid2.add(llab5);
			
			grid2.add(lab6);
			grid2.add(llab6);
			
			grid2.add(lab7);
			grid2.add(llab7);
			
			grid2.add(lab8);
			grid2.add(llab8);
			
			grid3.add(grid1);
			grid3.add(grid2);
			
			JPanel descP = new JPanel();
			descP.add(lab9);
			descP.add(llab9Scroll);
			
			
			JPanel buttons = new JPanel();
			JButton cancel = new JButton("Cancel");
			JButton save = new JButton("Save");
			
			buttons.add(save);
			buttons.add(cancel);
			
			
			
			cancel.addActionListener(new ActionListener(){

				public void actionPerformed(ActionEvent ev) {	
					frame.setVisible(false);
				}
				
			});
			
			
			save.addActionListener(new ActionListener(){

				public void actionPerformed(ActionEvent ev) {	
					
					double price = 0 ;
					int stock = 0;
					String name = llab2.getText();
					String location = llab3.getText();
					String desc = llab9.getText();
					double disc = -1;
					Date date1 = null;
					
					try {
						date1 = toFormat.parse(llab8.getText());
						disc = Double.parseDouble(llab6.getText());
						
						stock = Integer.parseInt(llab4.getText());
						price = Double.parseDouble(llab5.getText());
					}
					catch (ParseException e) {}
					
					if(price==0) popupError("Invalid price");
					else if(stock==0) popupError("Invalid stock");
					else if(name.isEmpty()) popupError("Empty name");
					else if(location.isEmpty()) popupError("Empty location");
					else if(desc.isEmpty()) popupError("Empty description");
					else if(disc == -1) popupError("Invalid discount");
					else if(date1 == null) popupError("Invalid end date");
					else
					{
						int answer = JOptionPane.showConfirmDialog(frame, "Do you want to save ?","Confirm saving",JOptionPane.YES_NO_OPTION);
					
						if(answer == JOptionPane.YES_OPTION) 
						{
							product.setName(name);
							product.setLocation(location);
							product.setPrice(price);
							product.setDescription(desc);
							product.setStock(stock);
							product.setDiscount(disc, date1);
								
							frame.setVisible(false);
							reAddGrid();
						}
					}
				}
				
			});
			
			
			mainPanel.add(grid3);
			mainPanel.add(descP);
			mainPanel.add(buttons);
			
		}
		catch(Exception e){
			
		}
		
		frame.setContentPane(mainPanel);
		frame.setSize(new Dimension(400,300));
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		frame.setVisible(true);
		frame.setLocationRelativeTo(null);
	}
	
	
	private void popupError(String message)
	{
		JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.INFORMATION_MESSAGE);
	}
	
	
	private void reAddGrid()
	{
		panel.remove(1);
		panel.add(makeGridListProducts());
		panel.revalidate();
	}
	
	
	public JPanel makeProductsTab()
	{
		panel = new JPanel();
		
		JPanel firstPanel = new JPanel();
		firstPanel.add(makeSearchPanel());
		firstPanel.add(makeAddProductPanel());
		
		panel.add(firstPanel);
		panel.add(makeGridListProducts());
		
		return panel;
	}

	
	
	
	
	private int getSelectedProducts(JTable table)
	{
		int count=0;
		for(int i=0;i<table.getRowCount();i++)
		{
			if( (Boolean)table.getValueAt(i, 8) == true ) count++;
		}
		return count;
	}
	
	private void deleteSelectedProducts(JTable table)
	{
		for(int i=0;i<table.getRowCount();i++)
		{
			if( (Boolean)table.getValueAt(i, 8) == true )
			{
				int productID = (Integer)table.getValueAt(i, 0);
				productCtr.removeProduct(productID);
			}
		}
		reAddGrid();
	}
}
